import React, { useState, useEffect } from 'react';
import { Layout, Menu, Avatar, Dropdown, Badge, Card, Row, Col, Statistic, List, Progress, Button, Space, Typography, message } from 'antd';
import {
  DashboardOutlined,
  UserOutlined,
  LogoutOutlined,
  BellOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  FileTextOutlined,
  SyncOutlined,
  DatabaseOutlined,
  ApiOutlined,
  TeamOutlined,
  BarChartOutlined,
  SettingOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  PlayCircleOutlined,
  ExclamationCircleOutlined
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { useAuthStore } from '@/stores/authStore';
import { dashboardService, DashboardStats, RecentTask, Notification } from '@/services/dashboardService';
import { LineChart, BarChart, PieChart, AreaChart } from '@/components/charts';
import type { LineChartData, BarChartData, PieChartData, AreaChartData } from '@/components/charts';
import { NotificationBell } from '@/components/notification';
import axios from 'axios';

const { Header, Sider, Content } = Layout;
const { Title, Text } = Typography;

export default function Dashboard() {
  const [collapsed, setCollapsed] = useState(false);
  const [stats, setStats] = useState<DashboardStats>({
    pendingTasks: 0,
    todayNewTasks: 0,
    todayCompletedTasks: 0,
    totalPendingTasks: 0,
    totalTodayNewTasks: 0,
    totalTodayCompletedTasks: 0,
    taskCategoryStats: [],
    taskTypeStats: [],
    topCreators: [],
    topAssignees: []
  });
  const [recentTasks, setRecentTasks] = useState<RecentTask[]>([]);
  const [notifications, setNotifications] = useState<Notification[]>([]);
  const [loading, setLoading] = useState(true);
  
  // 图表数据状态
  const [taskTrendData, setTaskTrendData] = useState<LineChartData[]>([]);
  const [taskStatusData, setTaskStatusData] = useState<PieChartData[]>([]);
  const [workflowStatsData, setWorkflowStatsData] = useState<BarChartData[]>([]);
  const [dataSyncTrendData, setDataSyncTrendData] = useState<AreaChartData[]>([]);
  const [chartLoading, setChartLoading] = useState(true);
  
  // 未读通知数量
  const unreadNotifications = notifications.filter(n => !n.read).length;
  
  const navigate = useNavigate();
  const { user, logout } = useAuthStore();

  useEffect(() => {
    loadDashboardData();
    loadChartData();
    
    // 设置定时刷新（每30秒）
    const interval = setInterval(() => {
      loadDashboardData();
      loadChartData();
    }, 30000);
    
    return () => clearInterval(interval);
  }, []);

  const loadDashboardData = async () => {
    try {
      setLoading(true);
      const [statsData, tasksData, notificationsData, completionTrendData, avgProcessingTimeData] = await Promise.all([
        dashboardService.getDashboardStats(),
        dashboardService.getRecentTasks(5),
        dashboardService.getNotifications({ page: 0, size: 10 }),
        dashboardService.getCompletionTrend({ days: 7 }),
        dashboardService.getAverageProcessingTime({ days: 7 })
      ]);
      
      // 处理通知数据结构
      const notificationList = Array.isArray(notificationsData) ? notificationsData : notificationsData.content || [];
      
      setStats(statsData);
      setRecentTasks(tasksData);
      setNotifications(notificationList);
      
      // 更新图表数据
      updateChartDataFromApi(statsData, completionTrendData, avgProcessingTimeData);
    } catch (error: any) {
      console.error('加载仪表板数据失败:', error);
      
      if (axios.isAxiosError(error)) {
        switch (error.response?.status) {
          case 401:
            message.error('登录已过期，请重新登录');
            logout();
            navigate('/login');
            break;
          case 403:
            message.error('没有权限访问该数据');
            break;
          case 500:
            message.error('服务器内部错误，请稍后再试');
            break;
          default:
            message.error('加载数据失败，请稍后再试');
        }
      } else if (error.request) {
        message.error('网络连接失败，请检查网络设置');
      } else {
        message.error('加载数据失败，请稍后再试');
      }
    } finally {
      setLoading(false);
    }
  };
  
  // 根据API数据更新图表数据
  const updateChartDataFromApi = (statsData: DashboardStats, completionTrendData: any[], avgProcessingTimeData: any) => {
    try {
      setChartLoading(true);
      
      // 任务趋势数据 - 基于完成率趋势数据
      if (completionTrendData && completionTrendData.length > 0) {
        setTaskTrendData([
          {
            name: '任务完成率',
            data: completionTrendData.map(item => item.completionRate || 0),
            color: '#52c41a'
          }
        ]);
      }
      
      // 任务状态分布数据 - 基于统计数据
      const pendingCount = statsData.pendingTasks || statsData.totalPendingTasks || 0;
      const todayCompleted = statsData.todayCompletedTasks || statsData.totalTodayCompletedTasks || 0;
      const todayNew = statsData.todayNewTasks || statsData.totalTodayNewTasks || 0;
      
      setTaskStatusData([
        { name: '待处理', value: pendingCount, color: '#faad14' },
        { name: '今日新增', value: todayNew, color: '#1890ff' },
        { name: '今日完成', value: todayCompleted, color: '#52c41a' }
      ]);
      
      // 任务分类统计数据
      if (statsData.taskCategoryStats && statsData.taskCategoryStats.length > 0) {
        setWorkflowStatsData([
          {
            name: '任务分类',
            data: statsData.taskCategoryStats.map(item => item.count),
            color: '#722ed1'
          }
        ]);
      }
      
      // Top创建者和执行者数据
      if (statsData.topCreators && statsData.topAssignees) {
        setDataSyncTrendData([
          {
            name: 'Top创建者',
            data: statsData.topCreators.slice(0, 7).map(item => item.count),
            color: '#52c41a',
            stack: 'total'
          },
          {
            name: 'Top执行者',
            data: statsData.topAssignees.slice(0, 7).map(item => item.count),
            color: '#1890ff',
            stack: 'total'
          }
        ]);
      }
      
    } catch (error) {
      console.error('更新图表数据失败:', error);
    } finally {
      setChartLoading(false);
    }
  };

  // 加载图表数据（保留作为备用）
  const loadChartData = async () => {
    // 图表数据现在通过loadDashboardData中的updateChartDataFromApi更新
    // 这个函数保留用于手动刷新
    try {
      const [completionTrendData, avgProcessingTimeData] = await Promise.all([
        dashboardService.getCompletionTrend({ days: 7 }),
        dashboardService.getAverageProcessingTime({ days: 7 })
      ]);
      
      updateChartDataFromApi(stats, completionTrendData, avgProcessingTimeData);
    } catch (error) {
      console.error('加载图表数据失败:', error);
    }
  };

  const handleLogout = () => {
    logout();
    navigate('/login');
  };

  const handleMenuClick = (key: string) => {
    switch (key) {
      case 'dashboard':
        navigate('/dashboard');
        break;
      case 'tasks':
        navigate('/tasks');
        break;
      case 'workflows':
        navigate('/workflows');
        break;
      case 'forms':
        message.info('表单设计功能开发中...');
        break;
      case 'data-sync':
        message.info('数据同步功能开发中...');
        break;
      case 'integrations':
        message.info('第三方集成功能开发中...');
        break;
      case 'users':
        message.info('用户管理功能开发中...');
        break;
      case 'organizations':
        message.info('组织架构功能开发中...');
        break;
      case 'reports':
        message.info('报表分析功能开发中...');
        break;
      case 'settings':
        message.info('系统设置功能开发中...');
        break;
      default:
        break;
    }
  };

  const menuItems = [
    {
      key: 'dashboard',
      icon: <DashboardOutlined />,
      label: '仪表板'
    },
    {
      key: 'tasks',
      icon: <FileTextOutlined />,
      label: '任务管理'
    },
    {
      key: 'workflows',
      icon: <SyncOutlined />,
      label: '工作流'
    },
    {
      key: 'forms',
      icon: <FileTextOutlined />,
      label: '表单设计'
    },
    {
      key: 'data-sync',
      icon: <DatabaseOutlined />,
      label: '数据同步'
    },
    {
      key: 'integrations',
      icon: <ApiOutlined />,
      label: '第三方集成'
    },
    {
      key: 'users',
      icon: <UserOutlined />,
      label: '用户管理'
    },
    {
      key: 'organizations',
      icon: <TeamOutlined />,
      label: '组织架构'
    },
    {
      key: 'reports',
      icon: <BarChartOutlined />,
      label: '报表分析'
    },
    {
      key: 'settings',
      icon: <SettingOutlined />,
      label: '系统设置'
    }
  ];

  const userMenuItems = [
    {
      key: 'profile',
      label: '个人资料',
      icon: <UserOutlined />
    },
    {
      key: 'settings',
      label: '设置',
      icon: <SettingOutlined />
    },
    {
      type: 'divider' as const
    },
    {
      key: 'logout',
      label: '退出登录',
      icon: <LogoutOutlined />,
      onClick: handleLogout
    }
  ];

  const getStatusText = (status: string) => {
    switch (status) {
      case 'created': return '已创建';
      case 'assigned': return '已分配';
      case 'in_progress': return '进行中';
      case 'suspended': return '已暂停';
      case 'completed': return '已完成';
      case 'cancelled': return '已取消';
      case 'rejected': return '已驳回';
      default: return '未知';
    }
  };
  
  // 刷新图表数据
  const refreshChartData = () => {
    loadChartData();
    message.success('图表数据已刷新');
  };
  
  // 生成时间轴数据
  const getTimeAxisData = () => {
    return Array.from({ length: 7 }, (_, i) => {
      const date = new Date();
      date.setDate(date.getDate() - 6 + i);
      return date.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' });
    });
  };

  const timeAxisData = getTimeAxisData();

  return (
    <Layout className="min-h-screen">
      <Sider 
        trigger={null} 
        collapsible 
        collapsed={collapsed}
        className="bg-white shadow-lg"
        width={240}
      >
        <div className="p-4">
          <div className="flex items-center justify-center">
            <div className="flex items-center space-x-2">
              <div className="w-8 h-8 bg-gradient-to-r from-blue-600 to-purple-600 rounded-lg flex items-center justify-center">
                <svg className="w-5 h-5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" />
                </svg>
              </div>
              {!collapsed && (
                <span className="text-xl font-bold text-gray-800">UniFlow</span>
              )}
            </div>
          </div>
        </div>
        
        <Menu
          mode="inline"
          defaultSelectedKeys={['dashboard']}
          items={menuItems}
          className="border-r-0"
          onClick={({ key }) => handleMenuClick(key)}
        />
      </Sider>
      
      <Layout>
        <Header className="bg-white shadow-sm px-6 flex items-center justify-between">
          <Button
            type="text"
            icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
            onClick={() => setCollapsed(!collapsed)}
            className="text-lg"
          />
          
          <div className="flex items-center space-x-4">
            <NotificationBell className="text-lg" />
            
            <Dropdown menu={{ items: userMenuItems }} placement="bottomRight">
              <div className="flex items-center space-x-2 cursor-pointer hover:bg-gray-50 px-3 py-2 rounded-lg">
                <Avatar 
                  src={user?.avatar} 
                  icon={<UserOutlined />}
                  size="small"
                />
                <span className="text-gray-700">{user?.name || user?.username}</span>
              </div>
            </Dropdown>
          </div>
        </Header>
        
        <Content className="p-6 bg-gray-50">
          <div className="mb-6">
            <Title level={2} className="mb-2">仪表板</Title>
            <Text type="secondary">欢迎回来，{user?.name || user?.username}！</Text>
          </div>
          
          {/* 统计卡片 */}
          <Row gutter={[16, 16]} className="mb-6">
            <Col xs={24} sm={12} lg={6}>
              <Card>
                <Statistic
                  title="总任务数"
                  value={stats.totalTasks}
                  prefix={<FileTextOutlined />}
                  valueStyle={{ color: '#1890ff' }}
                />
              </Card>
            </Col>
            <Col xs={24} sm={12} lg={6}>
              <Card>
                <Statistic
                  title="待处理任务"
                  value={stats.pendingTasks || stats.totalPendingTasks || 0}
                  prefix={<ClockCircleOutlined />}
                  valueStyle={{ color: '#faad14' }}
                />
              </Card>
            </Col>
            <Col xs={24} sm={12} lg={6}>
              <Card>
                <Statistic
                  title="今日新增任务"
                  value={stats.todayNewTasks || stats.totalTodayNewTasks || 0}
                  prefix={<SyncOutlined spin />}
                  valueStyle={{ color: '#1890ff' }}
                />
              </Card>
            </Col>
            <Col xs={24} sm={12} lg={6}>
              <Card>
                <Statistic
                  title="今日完成任务"
                  value={stats.todayCompletedTasks || stats.totalTodayCompletedTasks || 0}
                  prefix={<CheckCircleOutlined />}
                  valueStyle={{ color: '#52c41a' }}
                />
              </Card>
            </Col>
          </Row>
          
          <Row gutter={[16, 16]} className="mb-6">
            <Col xs={24} sm={12} lg={6}>
              <Card>
                <Statistic
                  title="过期任务"
                  value={stats.overdueStats?.totalOverdue || 0}
                  prefix={<ExclamationCircleOutlined />}
                  valueStyle={{ color: '#ff4d4f' }}
                />
              </Card>
            </Col>
            <Col xs={24} sm={12} lg={6}>
              <Card>
                <Statistic
                  title="任务分类数"
                  value={stats.taskCategoryStats?.length || 0}
                  prefix={<BarChartOutlined />}
                  valueStyle={{ color: '#722ed1' }}
                />
              </Card>
            </Col>
            <Col xs={24} sm={12} lg={6}>
              <Card>
                <Statistic
                  title="任务类型数"
                  value={stats.taskTypeStats?.length || 0}
                  prefix={<FileTextOutlined />}
                  valueStyle={{ color: '#13c2c2' }}
                />
              </Card>
            </Col>
            <Col xs={24} sm={12} lg={6}>
              <Card>
                <Statistic
                  title="活跃创建者"
                  value={stats.topCreators?.length || 0}
                  prefix={<TeamOutlined />}
                  valueStyle={{ color: '#eb2f96' }}
                />
              </Card>
            </Col>
          </Row>
          
          {/* 图表展示区域 */}
          <Row gutter={[16, 16]} className="mb-6">
            <Col xs={24} lg={12}>
              <LineChart
                title="任务趋势"
                subtitle="最近7天任务创建和完成趋势"
                data={taskTrendData}
                xAxisData={timeAxisData}
                loading={chartLoading}
                height={300}
                smooth={true}
                showArea={false}
                onRefresh={refreshChartData}
              />
            </Col>
            <Col xs={24} lg={12}>
              <PieChart
                title="任务状态分布"
                subtitle="当前任务状态占比"
                data={taskStatusData}
                loading={chartLoading}
                height={300}
                radius={['40%', '70%']}
                onRefresh={refreshChartData}
              />
            </Col>
          </Row>
          
          <Row gutter={[16, 16]} className="mb-6">
            <Col xs={24} lg={12}>
              <BarChart
                title="工作流执行统计"
                subtitle="最近7天工作流执行次数"
                data={workflowStatsData}
                xAxisData={timeAxisData}
                loading={chartLoading}
                height={300}
                onRefresh={refreshChartData}
              />
            </Col>
            <Col xs={24} lg={12}>
              <AreaChart
                title="数据同步趋势"
                subtitle="最近7天数据同步成功/失败趋势"
                data={dataSyncTrendData}
                xAxisData={timeAxisData}
                loading={chartLoading}
                height={300}
                stacked={true}
                onRefresh={refreshChartData}
              />
            </Col>
          </Row>
          
          {/* 原有的任务列表和通知区域 */}
          <Row gutter={[16, 16]}>
            <Col xs={24} lg={12}>
              <Card title="最近任务" extra={<Button type="link">查看全部</Button>}>
                <List
                  dataSource={recentTasks}
                  renderItem={(task) => (
                    <List.Item>
                      <List.Item.Meta
                        title={task.name}
                        description={
                          <Space>
                            <span>{getStatusText(task.status)}</span>
                            <span>•</span>
                            <span>{task.assignee}</span>
                            <span>•</span>
                            <span>{task.dueDate}</span>
                          </Space>
                        }
                      />
                      <Progress percent={task.progress} size="small" style={{ width: 100 }} />
                    </List.Item>
                  )}
                />
              </Card>
            </Col>
            <Col xs={24} lg={12}>
              <Card title="系统通知" extra={<Badge count={unreadNotifications} />}>
                <List
                  dataSource={notifications.slice(0, 5)}
                  renderItem={(notification) => (
                    <List.Item>
                      <List.Item.Meta
                        avatar={
                          <div className={`w-2 h-2 rounded-full ${
                            notification.read ? 'bg-gray-300' : 'bg-red-500'
                          }`} />
                        }
                        title={notification.title}
                        description={
                          <Space>
                            <span>{notification.content}</span>
                            <span>•</span>
                            <span>{notification.time}</span>
                          </Space>
                        }
                      />
                    </List.Item>
                  )}
                />
              </Card>
            </Col>
          </Row>
        </Content>
      </Layout>
    </Layout>
  );
}